package com.hicorp.segment.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hicorp.segment.pojo.po.BackendApi;
import com.hicorp.segment.pojo.po.Menu;
import com.hicorp.segment.service.BackendApiService;
import com.hicorp.segment.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: wqs
 * @Date: Created in 8:44 2021/5/31
 * @Description:
 * @ChineseDescription:
 * @Modified_By:
 */
@Component
@Order(1)
@Slf4j
public class InitMethod implements CommandLineRunner {

    private final MenuService menuService;

    private final BackendApiService backendApiService;


    public InitMethod(MenuService menuService, BackendApiService backendApiService) {
        this.menuService = menuService;
        this.backendApiService = backendApiService;
    }

    // 初始化 menu 表数据, 并为超级管理员添加所有页面访问权限
    public void initMenu(String fileName) {
        String json = FileOption.readJsonFile(fileName);
        List<Menu> menus = JsonUtil.decode(json, new TypeReference<>() {
        });
        assert menus != null;
        menuService.dataSave(menus);
    }

    // 初始化后端接口及接口相关关系.
    public void initApi(String fileName) {
        String backendApiJson = FileOption.readJsonFile(fileName);
        List<BackendApi> backendApiList = JsonUtil.decode(backendApiJson, new TypeReference<>() {
        });
        assert backendApiList != null;
        backendApiService.backendApiInit(backendApiList);
    }

    @Override
    public void run(String... args) {
        // 初始化菜单
        this.initMenu("menu.json");
        // 写入新的backendApi内容
//        this.initApi("backend-api.json");
        System.out.println("### INIT_TIPS: init resources by implements ApplicationRunner");
    }
}
